package com.ktgj.customer.controller;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.common.sms.service.CHttpPost;
import com.ktgj.customer.domain.Customer;
import com.ktgj.customer.domain.Employee;
import com.ktgj.customer.service.ICustomerService;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.sms.api.RemoteSmsTemplateService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.Map;

/**
 * 登录接口
 *
 * @author ruoyi
 */
@ControllerAdvice
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController {
    @Autowired
    private ILoginService loginService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ICustomerService customerService;

    /**
     * 员工端登录接口
     */
//    @PreAuthorize(hasPermi = "customer:login:employeeLogin")
    @PostMapping(value = "/employeeLogin")
//    @ExceptionHandler(Exception.class)
    public AjaxResult employeeLogin(@RequestBody Map<String, Object> map) {
        if (map.get("loginId") != null && !map.get("loginId").equals("") &&
                map.get("loginPwd") != null && !map.get("loginPwd").equals("")){
            Employee employee;
            try {
                employee = loginService.employeeLogin(map.get("loginId").toString(), map.get("loginPwd").toString());
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            if (employee != null) {
                return AjaxResult.success(employee);
            } else {
                return AjaxResult.error("账号密码错误");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 根据token获取员工信息
     */
//    @SignatureValidation
    //@PreAuthorize(hasPermi = "customer:login:employeeByToken")
    @PostMapping(value = "/employeeByToken")
    public AjaxResult employeeByToken(HttpServletRequest request) {
        Employee employee;
        try {
            employee = loginService.getLoginEmployee(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (employee != null) {
            return AjaxResult.success(employee);
        } else {
            return AjaxResult.error("01002", "登录已过期");
        }
    }

    /**
     * 根据token获取员工信息
     */
    //@PreAuthorize(hasPermi = "customer:login:employeeByToken")
    @PostMapping(value = "/getLoginEmployeeByToken")
    public AjaxResult getLoginEmployeeByToken(@RequestParam("token")String token) {
        Employee employee;
        try {
            employee = loginService.getLoginEmployeeByToken(token);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (employee != null) {
            return AjaxResult.success(employee);
        } else {
            return AjaxResult.error("01002", "登录已过期");
        }
    }

    /**
     * 用户端 会员修改账密码接口
     */
//    @SignatureValidation
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long customerId;
        int pwd;
        try {
            customerId = loginService.getLoginCustomer(request).getCustomerId();
            pwd = loginService.updatePwd(customerId, map.get("pwd").toString());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (pwd > 0){
            return AjaxResult.success("修改成功");
        }
        else {
            return AjaxResult.success("修改失败");
        }
    }

    @PostMapping("/updatetrainPassword")
    public AjaxResult updatetrainPassword(@RequestParam("customerId") Long customerId, @RequestParam("trainPassword") String trainPassword) {
        return AjaxResult.success(loginService.updatetrainPassword(customerId, trainPassword));
    }

    /**
     * 用户端app 账号密码登录的登录接口
     */
    @PostMapping(value = "/customerLogin")
    public AjaxResult customerLogin(@RequestBody Map<String, Object> map) {
        Customer customer;
        try {
            customer = loginService.customerLogin(map.get("loginId").toString(), map.get("loginPwd").toString());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (customer != null) {
            return AjaxResult.success(customer);
        } else {
            return AjaxResult.error("01001", "账号密码错误");
        }
    }

    /**
     * 用户端app根据token获取用户信息
     */
    //@SignatureValidation
    @PostMapping(value = "/customerByToken")
    public AjaxResult customerByToken(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (customer != null) {
            return AjaxResult.success(customer);
        } else {
            return AjaxResult.error("01002", "登录已过期");
        }
    }

    /**
     * 用户端app根据token获取用户信息
     */
    @PostMapping(value = "/getLoginCustomerByToken")
    public AjaxResult getLoginCustomerByToken(@RequestParam("token")String token) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomerByToken(token);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (customer != null) {
            return AjaxResult.success(customer);
        } else {
            return AjaxResult.error("01002", "登录已过期");
        }
    }

    /**
     * 用户端手机号登录
     */
    @PostMapping(value = "/customerPhoneLogin")
    public AjaxResult customerPhoneLogin(@RequestBody Map<String, Object> map) {
        Customer customer;
        try {
            customer = loginService.customerPhoneLogin(map.get("phone").toString(), map.get("code").toString());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (customer != null) {
            return AjaxResult.success(customer);
        } else {
            return AjaxResult.error("01001", "验证码输入错误");
        }
    }


    /**
     * 短信验证码发送接口
     */
    @PostMapping(value = "/smsLoginCode")
    public AjaxResult smsLoginCode(@RequestBody Map<String, Object> map) {
        String state;
        try {
            state = loginService.smsLoginCode(map.get("phone").toString());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (state.equals("success")) {
            return AjaxResult.success("01000", "发送成功");
        } else if (state.equals("limit")) {
            return AjaxResult.error("01003", "今日发送验证码次数已达上限");
        } else {
            return AjaxResult.error("01004", "验证码发送失败，请重试");
        }
    }

    /**
     * 会员短信修改密码验证
     * */
    @PostMapping("/shortMessageVerify")
    public AjaxResult shortMessageVerify(HttpServletRequest request, @RequestBody Map<String, Object> map){
        if (map.get("phone") != null && !map.get("phone").equals("") &&
                map.get("code") != null && !map.get("code").equals("")){
            String token = request.getHeader("token");
            Customer customer;
            try {
                customer = loginService.getLoginCustomerByToken(token);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            String phone = map.get("phone").toString();
            String code = map.get("code").toString();
            String redisCode = redisService.getCacheObject(phone + "Code");
            if (redisCode == null) {
                return AjaxResult.error("500", "验证码已过期，请重新发送");
            }
            else if (!redisCode.equals(code)) {
                return AjaxResult.error("500", "验证码输入错误");
            }
            else {
                if (customer != null && customer.getCustomerId() != null && customer.getCustomerId() != 0 &&
                        customer.getCustLoginPswmd5() != null && !customer.getCustLoginPswmd5().equals("")){
                    if (map.get("newPwdOne") != null && !map.get("newPwdOne").equals("") &&
                            map.get("newPwdTwo") != null && !map.get("newPwdTwo").equals("")){
                        String newPwdOne = map.get("newPwdOne").toString();
                        String newPwdTwo = map.get("newPwdTwo").toString();
                        int i;
                        try {
                            i = loginService.updatePwd(newPwdOne, newPwdTwo, customer);
                        } catch (Exception e){
                            return AjaxResult.error(e.getMessage());
                        }

                        if (i > 0){
                            return AjaxResult.success("200", "修改成功");
                        }
                        else {
                            return AjaxResult.error("500", "修改失败");
                        }
                    }
                    else {
                        return AjaxResult.error("500", "缺少必要参数");
                    }
                }
                else {
                    return AjaxResult.error("500", "未查到会员信息");
                }
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 小程序用户身份验证
     * openId 小程序用户Id
     */
//    @SignatureValidation
    @PostMapping("/appletAuth")
    public AjaxResult appletAuth(HttpServletRequest request,@RequestBody Map<String,String> map){
        Strings.isNotEmpty(map.get("code"));
        AjaxResult code;
        try {
            code = loginService.appletAuth(map.get("code"), request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return code;
    }

    /**
     * 小程序手机号解密
     */
    @PostMapping("/appletDecodePhone")
    public AjaxResult appletDecodePhone(@RequestBody Map<String,String> map){
        return loginService.appletDecodePhone(map);
    }

    /**
     * 短信验证码发送接口
     */
    @PostMapping(value = "/verificationSmsLoginCode")
    public String verificationSmsLoginCode(@RequestParam String phone) {
        String state = loginService.smsLoginCode(phone);
        if (state.equals("success")) {
            return success().toString();
        } else if (state.equals("limit")) {
            return "今日发送验证码次数已达上限";
        } else {
            return "验证码发送失败，请重试";
        }
    }

    /**
     * 头像、昵称、性别、地区
     */

    @PostMapping("/appletLogin")
    public AjaxResult appletLogin(@RequestBody Map<String, String> map) {
        String profileAvatar = map.get("profileAvatar");
        String nickname = map.get("nickname");
        String phone = map.get("phone");
        String openId = map.get("openId");
        return AjaxResult.success(loginService.appletLogin(profileAvatar, nickname, phone, openId));
    }

    /**
     * 员工修改密码
     * */
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(HttpServletRequest request, @RequestBody Map<String, Object> map){
        if (map.get("oldPwd") != null && !map.get("oldPwd").equals("") &&
                map.get("newPwdOne") != null && !map.get("newPwdOne").equals("") &&
                map.get("newPwdTwo") != null && !map.get("newPwdTwo").equals("")){
            String oldPwd = map.get("oldPwd").toString();
            String newPwdOne = map.get("newPwdOne").toString();
            String newPwdTwo = map.get("newPwdTwo").toString();
            int i;
            try {
                i = loginService.updatePassword(request, oldPwd, newPwdOne, newPwdTwo);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            if (i > 0){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.error("修改失败");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 员工退出登录
     * @param request
     * @return
     */
    @PostMapping("/logOut")
    public AjaxResult logOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token != null && !token.equals("")) {
            boolean logOut = loginService.logOut(token);
            if (logOut)
                return AjaxResult.success("退出登录成功！");
            else
                return AjaxResult.error("您当前未登录！");
        } else {
            return AjaxResult.error("token不能为空！");
        }
    }
}
